package com.shiro;

import com.alibaba.fastjson.JSONObject;
import com.bean.ResponseBean;
import com.pojo.Admin;
import com.pojo.Jiedairen;
import com.pojo.Log;
import com.service.LogService;
import com.service.PermissionService;
import com.util.IPUtil;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class SessionFilter extends BasicHttpAuthenticationFilter {

    private ApplicationContext ctx ;
    private List<String> kefuPermission = Arrays.asList("/kefu/kefuLogin","/kefu/pandeng_kefu","/kefu/quitLogin","/zixun/getunhandled","/zixun/getall","/zixun/getDetail","/zixun/updateInfo","/websocket");


    public SessionFilter(ApplicationContext ctx){
        this.ctx = ctx ;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse response, Object mappedValue) {
        try {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String url = ((HttpServletRequest) request).getRequestURI();
            String username = null ;

            //---------------------------------------不写日志的定时器--------------------
            String[] urls= {"/zhiyeChange/selectZhiyeChangeByPage",
                    "/zanzhuzheng/geAfterDueTimeZanzhuzheng",
                    "/zanzhuzheng/getBeforeDueTimeZanzhuzheng",
                    "/workCard/getBeforeDueTimeWorkCard",
                    "/businessStaff/getBusinessStaffSp",
                    "/qiye/jiJiangDaoQiQiye",
                    "/qiye/yidaoqiQiye"
            };
            for (String u:urls){
                if (url.trim().startsWith(u)){
                    return true;
                }
            }
            //----------------------------------------end ------------------------------


            Admin userinfo = (Admin) request.getSession().getAttribute("admin");
            Jiedairen kefu = (Jiedairen) request.getSession().getAttribute("kefu");



            if (userinfo==null && kefu == null){
                return false;
            }
            LogService logService = ctx.getBean(LogService.class) ;
            PermissionService permissionService = ctx.getBean(PermissionService.class) ;

            if (kefu != null) {
                if(kefuPermission.contains(url.trim())) {
//                    System.out.println("物业登录");
                    username = kefu.getJdname();
                    // 记录权限
                    String name = permissionService.getPermissionByUrl(url) ;

                    UsernameAuth usernameAuth = new UsernameAuth("*&**&kefu");
                    getSubject(request, response).login(usernameAuth);
                    getSubject(request, response).checkPermission(url);
                    return true ;
                }
            }

            if(userinfo==null){
                return false;
            }
            username = userinfo.getUsername();

            UsernameAuth usernameAuth = new UsernameAuth(username);
            getSubject(request, response).login(usernameAuth);  //登录
            try{
                getSubject(request, response).checkPermission(url);
            }catch(AuthorizationException e){
                return false ;
            }//权限

            String name = permissionService.getPermissionByUrl(url) ;

            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }


    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;
        //httpServletResponse.setStatus(401);
        ResponseBean result = new ResponseBean();
        result.setCode(401);
        result.setMsg("拒绝访问");
        result.setCount(0L);
        result.setData(null);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println(JSONObject.toJSONString(result));
        return false;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.addHeader("Access-Control-Allow-Headers", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
        httpServletResponse.addHeader("Access-Control-Expose-Headers", "token");

        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }

        return super.preHandle(request,response);
    }
}
